var study = function () {
    var tags = [],
        buttonAddTerm;
    return {
        getCloudTags : function (tags) {
            $("#cloud-tags").jQCloud(tags);
        },
        addTerm: function () {
            study.createTerm();
        },
        createTerm: function () {
            $.post('/ajax/createterm', {}, function (data) {
                if (data.result == 'ok') {
                    study.getForm(data.id, 'term', 'add');
                }
            });
        },
        deleteTerm: function (id) {
            if (!id) {
                return;
            }

            var blockTerm = $('#term-id-'+ id +'');
            $.post('/ajax/deleteterm', {"term_id" : id}, function (data) {
                if (data.result == 'ok') {

                    if (blockTerm.length) {
                        blockTerm.hide('slow');
                    }

                    mn.notify('success', {text: "Термин удален"});
                }
            });
        },
        deleteTermForm: function (id) {
            study.deleteTerm(id);
            modal.close();
        },
        getForm: function (id, type, mode) {
            var title = '';
            switch (mode) {
                case 'add':
                    title = 'Добавить термин';
                    break;
                case 'edit':
                    title = 'Редактировать термин';
                    break;
            }

            $.get('/ajax/getform',{"id": id, "type": type}, function (data) {
                modal.open(data.html, {"title": title});
                return null;
            });
        },
        editTerm: function (id) {
            study.getForm(id, 'term', 'edit');
        },
        saveTerm: function () {
            var title = $('#term-title').val(),
                first = $('#term-symbol').val(),
                info  = $('#term-content').val(),
                id = $('#term-id').val();

            $.post('/ajax/saveterm',{"term_id":id,"tags":tags,"first_symbol":first,"name_term":title,"info":info}, function (data) {
                if (data.result == 'ok') {
                    modal.close();
                    mn.notify('success', {"text" :"Изменения сохранены"});
                }
            }
        );

        },
        getTerm: function (termId) {
            $.get('/ajax/getTerm',{"term_id": termId}, function (data) {
                if (data.result == 'ok') {
                    return data.term;
                }

                return null;
            });

            return null;
        },
        showFormNewTag: function (el) {
            buttonAddTerm = $(el);
            var termId        = buttonAddTerm.attr('data-term'),
                form          = buttonAddTerm.parents('.form-tag').html('<input type="text" data-term="' + termId + '" class="input-small input-tag" name="tag">');

            if (!termId) {
                console.log($(el));
                return false;
            }

            $('.input-tag').typeahead({source: study.getTags()}).focusout(
                    function (event) {
                        study.addTag(this);
                    }
                ).keypress(
                function(e) {
                    if (e.keyCode == 13) {
                        study.addTag(this);
                    }
                }
            );

            return true;
        },
        addTag: function (element) {
            var inputEl  = $(element),
                tag_name = inputEl.val(),
                term_id  = inputEl.attr('data-term'), html = '';

            if (!tag_name || !term_id) {
                console.log($(element));
                return;
            }

            $.post('/ajax/addtag/', {"tag": tag_name, "term_id": term_id}, function (data) {
                if (data.result == 'ok' && data.tag_id) {
                    html = '<span class="label"><a class="label" href="/study/?tag='+ data.tag_id + '">' + tag_name + '</a>'
                         + '<i title="Удалить" class="icon-trash" onclick="study.deleteTag(' + data.tag_id + ','+buttonAddTerm.attr('data-term') + '  , this)">'
                         + '</i></span><span class="form-tag">'
                         + buttonAddTerm.clone().wrap('<div></div>').parent().html() + '</span>';
                    $(html).replaceAll(inputEl.parent());
                    mn.notify('success', {text: "Тег добавлен"});
                }
            });

        },
        deleteTag: function(tag_id, term_id, el) {
            $.post('/ajax/deletetag/', {"tag": tag_id, "term_id": term_id}, function (data) {
                if (data.result =='ok') {
                    $(el).parent().hide();
                    mn.notify('success', {text: "Тег удален"});
                }
            });
        },
        getTags: function () {
            if (tags.length) {
                return tags;
            } else {
                $.get('/ajax/getstudytags',{}, function (data) {
                    for (i in data.tags) {
                        if (data.tags[i].tag_name) {
                            tags.push(data.tags[i].tag_name);
                        }
                    }
                });
            }
            return tags;
        },
        searchTerm: function (el) {
            var query = $(el).val();

            if (query) {
                location.href = '/study?q=' + query;
            }

        },
        setAction: function (termId, action) {
            $.post('/ajax/setactionterm/', {'term_id': termId, "term_action" : action}, function () {
                mn.notify('success', 'Изменения сохранены');
            })
        }
    }
}();

$(document).ready(function () {
    $('#search-terms').keypress(function (event) {
        if (event.keyCode == 13) {
            study.searchTerm(this);
        }
    });
});